import _ from 'lodash';
import { tableSizeList } from './components/tableHeaderTools';

const equivalentControl = [
  { type: 'search', equivalentKey: 'LIKE' },
  { type: 'filter', equivalentKey: 'IN' },
  { type: 'sorter', equivalentKey: 'SORT' },
];
const availableControlType = _.concat(_.map(equivalentControl, 'type'), ['transfer']); // 可选的列操作

// 获取表格默认尺寸
export function getDefaultSize(size) {
  const defaultSize = 'middle';
  return _.includes(_.map(tableSizeList, 'key'), size) ? size : defaultSize;
}

// 获取表格头部属性
export function getHeaderOptions(opts) {
  if (!_.isEmpty(opts)) {
    if (_.isPlainObject(opts)) {
      const { headerTitle, headerToolsRender, headerButtonList, headerButtonClick } = opts;
      return {
        headerTitle: _.isString(headerTitle) ? headerTitle : '',
        isHeaderToolsRender: !!headerToolsRender,
        headerButtons: _.isArray(headerButtonList)
          ? _.filter(headerButtonList, ({ key, label }) => !!key && !!label)
          : [],
        headerButtonClick: typeof headerButtonClick === 'function' ? headerButtonClick : null,
      };
    } else if (_.isString(opts)) {
      return {
        headerTitle: opts,
        isHeaderToolsRender: true,
      };
    }
    return {
      headerTitle: '',
      isHeaderToolsRender: true,
    };
  }
  return {};
}

// 获取表格选择属性
export function getDefaultSelection(opts) {
  if (opts) {
    if (_.isPlainObject(opts)) {
      return _.assign(
        { isSelection: true, checkStrictly: opts.checkStrictly !== false },
        typeof opts.getCheckboxProps === 'function'
          ? { getCheckboxProps: opts.getCheckboxProps }
          : null,
      );
    }
    return { isSelection: true };
  }
  return { isSelection: false };
}

// 获取表格列规则(格式化fixed、 align、 width、columnControl，注入key、originalIndex)
export function getDefaultColumnSettings(columns, renderIndex, search) {
  // 获取search部分的操作，用来排除表格列的重复操作
  const invalidColumnTypes = _.isArray(search)
    ? _.assign(
        {},
        ..._.map(search, ({ key, searchType }) => ({
          [key]: _.find(equivalentControl, ({ equivalentKey }) => equivalentKey === searchType)
            ?.type,
        })),
      )
    : {};
  // 递归格式化
  const getDefaultColumns = (tree = [], result = [], fixed = false, index) => {
    if (!tree || !tree.length) return [];
    for (let i = 0; i < tree.length; i++) {
      const {
        fixed: currentFixed,
        align: currentAlign,
        width: currentWidth,
        columnControl: currentColumnControl,
        ...restObj
      } = tree[i];
      const targetFixed = fixed
        ? fixed
        : _.includes(['left', true], currentFixed)
        ? 'left'
        : currentFixed === 'right'
        ? 'right'
        : false;
      let node = {
        ...restObj,
        originalIndex: i,
        key: restObj.dataIndex + '&' + (index || '') + (i + 1),
        fixed: targetFixed,
      };
      if (tree[i].children && tree[i].children.length) {
        node.children = [];
        result.push(node);
        getDefaultColumns(
          tree[i].children,
          node.children,
          targetFixed,
          (index || '') + (i + 1) + '-',
        );
      } else {
        node.align = _.includes(['left', 'center', 'right'], currentAlign)
          ? currentAlign
          : 'center';
        if (/^\d+$/.test(currentWidth)) {
          node.width = Math.round(currentWidth);
        }
        if (_.isPlainObject(currentColumnControl)) {
          const { typeList, ...restColumnControlOpts } = currentColumnControl;
          const availableTypes = _.isArray(typeList)
            ? _.intersection(availableControlType, typeList)
            : _.includes(availableControlType, typeList)
            ? [typeList]
            : [];
          const usefulTypes = _.filter(
            availableTypes,
            (type) => type !== invalidColumnTypes[node.dataIndex],
          );
          if (usefulTypes.length) {
            node.columnControl = { typeList: usefulTypes, ...restColumnControlOpts };
          }
        }
        result.push(node);
      }
    }
    return result;
  };
  if (_.isArray(columns)) {
    const defaultColumns = getDefaultColumns(columns);
    const leftColumns = _.map(
      _.filter(defaultColumns, ({ fixed }) => fixed === 'left'),
      ({ key, title, originalIndex }) => ({ key, title, originalIndex, checked: true }),
    );
    const middleColumns = _.map(
      _.filter(defaultColumns, ({ fixed }) => !fixed),
      ({ key, title, originalIndex }) => ({ key, title, originalIndex, checked: true }),
    );
    const rightColumns = _.map(
      _.filter(defaultColumns, ({ fixed }) => fixed === 'right'),
      ({ key, title, originalIndex }) => ({ key, title, originalIndex, checked: true }),
    );
    if (renderIndex) {
      const indexColumn = {
        width: 80,
        key: 'index',
        title: '序号',
        dataIndex: 'index',
        align: 'center',
        originalIndex: -1,
        fixed: false,
      };
      if (leftColumns.length) {
        indexColumn.fixed = 'left';
        leftColumns.unshift(
          _.assign({ checked: true }, _.pick(indexColumn, ['key', 'title', 'originalIndex'])),
        );
      } else {
        middleColumns.unshift(
          _.assign({ checked: true }, _.pick(indexColumn, ['key', 'title', 'originalIndex'])),
        );
      }
      defaultColumns.unshift(indexColumn);
    }
    return { defaultColumns, defaultColumnSettings: { leftColumns, middleColumns, rightColumns } };
  }
  return {
    defaultColumns: [],
    defaultColumnSettings: { leftColumns: [], middleColumns: [], rightColumns: [] },
  };
}

// 格式化级联自节点固定样式
export function formatColumnChildrenFixed(obj, fixed, result = {}) {
  if (!obj) return;
  _.assign(result, obj, { fixed });
  if (result.children && result.children.length) {
    for (let i = 0; i < result.children.length; i++) {
      formatColumnChildrenFixed(result.children[i], fixed, result.children[i]);
    }
  }
  return result;
}

// 获取分页初始参数
export function getPaging(paging) {
  const defaultPagingParams = {
    size: 10,
    current: 1,
  };
  if (_.isBoolean(paging)) {
    return paging ? defaultPagingParams : _.assign({}, defaultPagingParams, { size: -1 });
  } else if (_.isPlainObject(paging)) {
    const { size } = paging;
    if (/^\d+$/.test(size) && size > 0) {
      return _.assign({}, defaultPagingParams, { size });
    } else {
      return _.assign({}, defaultPagingParams, { size: -1 });
    }
  }
  return _.assign({}, defaultPagingParams, { size: -1 });
}
